package com.thenie.web;

import com.thenie.pojo.Book;
import com.thenie.pojo.Page;
import com.thenie.service.BookService;
import com.thenie.service.impl.BookServiceImpl;
import com.thenie.utils.WebUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class BookServlet extends BaseServlet{
    BookService bookService=new BookServiceImpl();

    protected void page(HttpServletRequest req,HttpServletResponse resp){
        ServletContext servletContext = req.getServletContext();
        servletContext.getContextPath();
        try {
            Page<Book> bookPage =null;
            //1.获取当前页数，以及当前页数容量
            int pageNo=WebUtils.parseInt(req.getParameter("pageNo"),1);
            int pageSize=WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
            bookPage = bookService.page(pageNo, pageSize);

            bookPage.setUrl("manager/bookServlet?action=page");
            req.setAttribute("bookPage",bookPage);
            req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    protected void add(HttpServletRequest req, HttpServletResponse resp){
        //1.获取所添加的book信息
        Book book=new Book();
        WebUtils.copyParamToBean(req.getParameterMap(), book);
        //2.将图书信息添加到数据库
        bookService.addBook(book);
        //3.刷新页面
        this.page(req,resp);
    }
    protected void delete(HttpServletRequest req,HttpServletResponse resp){
        Integer id = Integer.valueOf(req.getParameter("id"));
        bookService.deleteBookById(id);

        this.page(req,resp);
    }
    protected void update(HttpServletRequest req,HttpServletResponse resp){
        Book book=new Book();
        WebUtils.copyParamToBean(req.getParameterMap(), book);

        bookService.updateBook(book);

        this.page(req,resp);
    }
    protected void list(HttpServletRequest req,HttpServletResponse resp){
        //1.通过bookService查询全部图书
        List<Book> books = bookService.queryBooks();
        //2.把全部图书保存到request域中
        req.setAttribute("books", books);
        //3.转发到图书馆里页面
        try {
            req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
}
